package com.haohan.jingyuan.customer.service;

import cn.hutool.json.JSONUtil;
import com.haohan.jingyuan.customer.dao.CustomerFileAuthMapper;
import com.haohan.jingyuan.customer.dao.CustomerFileMapper;
import com.haohan.jingyuan.customer.dao.CustomerGroupMapper;
import com.haohan.jingyuan.customer.dao.CustomerTagMapper;
import com.haohan.jingyuan.customer.entity.CustomerTag;
import com.haohan.jingyuan.customer.dto.req.VisitorLoginRequest;
import com.haohan.jingyuan.customer.dto.resp.VisitorFileInfoResp;
import com.haohan.jingyuan.customer.dto.resp.VisitorLoginResp;
import com.haohan.jingyuan.customer.entity.CustomerFile;
import com.haohan.jingyuan.customer.entity.CustomerFileAuth;
import com.haohan.jingyuan.customer.entity.CustomerGroupInfo;
import com.haohan.jingyuan.customer.helper.VisitorFileRespHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 客户访客服务实现类
 *
 * @ClassName CustomerVisitorService
 * @Description 客户访客相关业务逻辑实现
 * @Author hexijun
 * @Time 2025/11/05 15:00
 * @Version 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CustomerVisitorService {

    /**
     * 客户文件授权Mapper
     */
    private final CustomerFileAuthMapper customerFileAuthMapper;

    /**
     * 客户文件Mapper
     */
    private final CustomerFileMapper customerFileMapper;

    /**
     * 客户分组Mapper
     */
    private final CustomerGroupMapper customerGroupMapper;

    /**
     * 客户标签Mapper
     */
    private final CustomerTagMapper customerTagMapper;

    /**
     * 访客登录
     *
     * @param request 访客登录请求
     * @return 访客登录响应，包含按客户ID分组、文件按分组层级组织的数据
     */
    public VisitorLoginResp visitorLogin(VisitorLoginRequest request) {
        // 根据用户名和密码查询授权信息列表
        List<CustomerFileAuth> authList = customerFileAuthMapper.selectByUserNameAndPassword(
                request.getUsername(), request.getPassword());

        // 如果查询不到数据，登录失败
        if (CollectionUtils.isEmpty(authList)) {
            return null;
        }

        // 查询所有文件分组信息（type=2），用于构建层级结构
        List<CustomerGroupInfo> allGroups = customerGroupMapper.selectByType(2);
        Map<String, CustomerGroupInfo> groupMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(allGroups)) {
            groupMap = allGroups.stream()
                    .collect(Collectors.toMap(CustomerGroupInfo::getGroupId, group -> group));
        }

        // 查询所有标签信息（type=2，客户材料标签）
        List<CustomerTag> allTags = customerTagMapper.selectByType(2);
        Map<String, CustomerTag> tagMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(allTags)) {
            tagMap = allTags.stream()
                    .collect(Collectors.toMap(CustomerTag::getTagCode, tag -> tag));
        }

        // 按customerId分组
        Map<String, List<CustomerFileAuth>> customerAuthMap = authList.stream()
                .collect(Collectors.groupingBy(CustomerFileAuth::getCustomerId));

        // 构建响应数据
        Map<String, List<VisitorFileInfoResp>> customerFilesMap = new HashMap<>();

        for (Map.Entry<String, List<CustomerFileAuth>> entry : customerAuthMap.entrySet()) {
            String customerId = entry.getKey();
            List<CustomerFileAuth> auths = entry.getValue();

            // 收集该客户的所有授权文件
            List<CustomerFile> allFiles = new ArrayList<>();

            for (CustomerFileAuth auth : auths) {
                List<CustomerFile> files = null;

                if (auth.getAuthType() == 1) {
                    // 授权类型为1：全部文件
                    files = customerFileMapper.selectByCustomerId(customerId);
                } else if (auth.getAuthType() == 2) {
                    // 授权类型为2：指定文件
                    if (auth.getFileIds() != null && !auth.getFileIds().trim().isEmpty()) {
                        List<String> fileKeys = JSONUtil.toList(auth.getFileIds(), String.class);
                        if (!CollectionUtils.isEmpty(fileKeys)) {
                            files = customerFileMapper.selectByFileKeys(fileKeys);
                        }
                    }
                }

                if (files != null && !CollectionUtils.isEmpty(files)) {
                    // 过滤出属于该客户的文件
                    List<CustomerFile> filteredFiles = files.stream()
                            .filter(file -> customerId.equals(file.getCustomerId()))
                            .collect(Collectors.toList());
                    if (!CollectionUtils.isEmpty(filteredFiles)) {
                        allFiles.addAll(filteredFiles);
                    }
                }
            }

            // 去重（根据fileKey）
            Map<String, CustomerFile> fileMap = new HashMap<>();
            for (CustomerFile file : allFiles) {
                if (!fileMap.containsKey(file.getFileKey())) {
                    fileMap.put(file.getFileKey(), file);
                }
            }
            List<CustomerFile> uniqueFiles = new ArrayList<>(fileMap.values());

            // 转换为层级结构的响应对象
            List<VisitorFileInfoResp> fileRespList = VisitorFileRespHelper.convert2VisitorFileInfoRespList(
                    uniqueFiles, groupMap, tagMap);

            customerFilesMap.put(customerId, fileRespList);
        }

        VisitorLoginResp loginResp = new VisitorLoginResp();
        loginResp.setCustomerFiles(customerFilesMap);

        return loginResp;
    }
}

